<template>
	<view class="content">
		<view class="LogoBox">
			<view class="Logo">
				<u--image class="img" :showLoading="true" src="../../static/image/Logo/Logo.png" width="120rpx"
					height="120rpx"></u--image>

				<view class="text" style="letter-spacing: 6px;">
					<!-- <text style="color: #e83333;">智能</text> -->
					<text style="color: #51d0d0;">汇创云</text>
					平台
				</view>
			</view>
		</view>

		<view class="FormBox">
			<uni-forms ref="baseForm" :modelValue="FormData" label-position="left" class="FormDataBox">

				<uni-forms-item name="Business_Code" style="margin-top: 50px;">
					<view style="display: flex;align-items: center;">
						<uni-icons fontFamily="CustomFontPlatform" color="#333"
							:size="20">{{$utils.toUniCode('&#xe75f;')}}</uni-icons>
						<uni-easyinput type="text" v-model="FormData.Business_Code" trim="all" @input="GetBusiness"
							:clearable="false" placeholder="请输入企业代号"></uni-easyinput>
					</view>
				</uni-forms-item>

				<uni-forms-item name="Business">
					<view style="display: flex;align-items: center;">
						<uni-icons fontFamily="CustomFontPlatform" color="#333"
							:size="20">{{$utils.toUniCode('&#xe64b;')}}</uni-icons>
						<uni-data-select v-model="FormData.Business" :localdata="BusinessList" :clear="false"
							@change="SelectBusiness" placeholder="请选择账套"></uni-data-select>
					</view>
				</uni-forms-item>

				<uni-forms-item name="UserAccount">
					<view style="display: flex;align-items: center;">
						<uni-icons fontFamily="CustomFontPlatform" color="#333"
							:size="20">{{$utils.toUniCode('&#xe649;')}}</uni-icons>

						<uni-easyinput type="text" v-model="FormData.UserAccount" trim="all" :clearable="false"
							placeholder="请输入账号"></uni-easyinput>
					</view>
				</uni-forms-item>

				<uni-forms-item name="UserPwd">
					<view style="display: flex;align-items: center;">
						<uni-icons fontFamily="CustomFontPlatform" color="#333"
							:size="20">{{$utils.toUniCode('&#xe60c;')}}</uni-icons>
						<uni-easyinput type="password" v-model="FormData.UserPwd" trim="all" :clearable="false"
							style="letter-spacing: 4px;" placeholder="请输入密码"></uni-easyinput>
					</view>
				</uni-forms-item>

				<uni-forms-item>
					<view class="x-bc">
						<view class="x-f">
							<checkbox-group @change="checkboxChange">
								<checkbox class="CheckBox" :checked="Remember" color="#fff"
									activeBackgroundColor="#51d0d0" activeBorderColor="#51d0d0">
									<view style="margin-left: 6px;">
										记住密码
									</view>
								</checkbox>
							</checkbox-group>

							<view @click="openWebInBrowser(1)" style="color: #51d0d0;margin-left: 10px;">用户协议</view>
							<view @click="openWebInBrowser(2)" style="color: #51d0d0;margin-left: 10px;">隐私政策</view>
						</view>


						<view class="" style="padding-right: 8rpx;color: #999;font-weight: 600;"
							@click="togetherBtn('enroll')">
							<text>注册</text>
						</view>
					</view>
				</uni-forms-item>

			</uni-forms>
		</view>

		<view class="BtnBox">

			<button class="LoginBtn" type="primary" :loading="IsLoading" :disabled="IsLoading" @click="LoginApp">
				<text class="Text">登录</text>
			</button>
		</view>


		<view class="BottomText">
			<text>—— ©汇智云创 技术支持 ——</text>

		</view>
	</view>
</template>

<script>
	const open = uni.requireNativePlugin("Html5App-openFile");
	// 更新APP用的
	// #ifdef APP-PLUS
	import MAPPUpdate from '@/uni_modules/mc-ui/components/m-app-update/js_sdk/appUpdate.js';
	// #endif
	export default {
		data() {
			return {
				datas: [50, 20],
				Only_Identity: '',
				IsLoading: false, // 登录加载状态
				FormData: {
					Business_Code: '', // 企业代号
					Business: '', // 账套
					UserAccount: '', // 账号
					UserPwd: '', // 密码
				},
				BusinessList: [], // 账套列表
				Remember: true, // 是否记住密码

				Timer: null,
				rules: { // 自定义校验
					Business_Code: {
						rules: [{
							required: true,
							errorMessage: ' '
						}]
					},
					Business: {
						rules: [{
							required: true,
							errorMessage: ' '
						}]
					},
					UserAccount: {
						rules: [{
							required: true,
							errorMessage: ' ',
						}]
					},
					UserPwd: {
						rules: [{
							required: true,
							errorMessage: ' ',
						}]
					}
				},

				listenFun: null,
				InterTime: null,
			}
		},
		onShow() {
			var that = this
			// 强制横屏
			plus.screen.lockOrientation('portrait-primary');

			uni.hideToast();

		},
		onLoad() {
			var that = this;

			let sysDeviceInfo = uni.getSystemInfoSync();

			that.$store.commit('ChangeAndSetStateData', {
				Name1: 'sysDeviceInfo',
				data: sysDeviceInfo,
				StorageName: 'sysDeviceInfo',
				StorageData: JSON.stringify(sysDeviceInfo),
			})

			if (!that.$utils.isEmpty(that.$store.state.UserInfo)) {
				let UserInfo = that.$store.state.UserInfo;

				that.FormData.Business_Code = UserInfo.Business_Code;
				that.FormData.Business = UserInfo.Business;
				that.FormData.UserAccount = UserInfo.UserAccount;

				that.GetBusiness(UserInfo.Business_Code);



				// 记住密码
				if (UserInfo.Remember) {
					that.FormData.UserPwd = UserInfo.UserPwd;
					that.Remember = true;

					if (uni.getStorageSync('Automatic_Login')) {
						that.checkNetworkAndSetup();
					}
				} else {
					that.FormData.UserPwd = '';
					that.Remember = false;
				}
			}

			that.GetOnlyIdentity() // 获取本机唯一标识


		},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.baseForm.setRules(this.rules);
		},
		mounted() {
			uni.getSystemInfo({
				success: function(res) {
					let safeArea = res.safeAreaInsets;
					uni.setStorageSync('safeAreaBottom', JSON.stringify(safeArea.bottom))
				}
			});
		},
		onUnload() {
			this.stopInterval(); // 停止定时器  
			if (this.listenFun !== null) {
				uni.offNetworkStatusChange(this.listenFun); // 移除网络状态变化监听器  
				this.listenFun = null; // 防止内存泄漏  
			}
		},
		methods: {
			togetherBtn() { // 注册
				uni.navigateTo({
					url: '/pages/login/enrollPage',
					// animationType: 'fade-in',
					// animationDuration: 50
				})
			},
			openWebInBrowser(id) { // 打开外链
				// #ifdef APP-PLUS  
				switch (id) {
					case 1: // 用户协议
						plus.runtime.openURL('http://mes.hzyc.org.cn:20050/download/html/汇创云平台用户协议.html');
						break;
					case 2: // 隐私政策
						plus.runtime.openURL('http://mes.hzyc.org.cn:20050/download/html/汇创云平台隐私政策.html');
						break;
					default:
						break;
				}
				// #endif  
			},
			tryLogin() {
				if (!this.$utils.isEmpty(this.FormData.Business)) {
					this.LoginApp();
					clearInterval(this.InterTime);
				}
			},
			checkNetworkAndSetup() {
				let that = this;
				uni.getNetworkType({
					success: (res) => {
						if (res.networkType !== 'none') {
							// 如果有网络连接，则设置定时器  
							that.startInterval();
						} else {
							// 如果没有网络连接，则注册网络状态变化监听器  
							if (that.listenFun === null) {
								that.listenFun = uni.onNetworkStatusChange((networkRes) => {
									if (networkRes.isConnected) {
										// 网络连接恢复时，启动定时器并移除监听器  
										that.startInterval();
										uni.offNetworkStatusChange(that.listenFun);
										that.listenFun = null; // 防止内存泄漏  
									}
								});
							}
						}
					},
					fail: (err) => {
						console.error('获取网络类型失败：', err);
					}
				});
			},
			// 启动定时器  
			startInterval() {
				let that = this;
				if (that.InterTime === null) {
					that.InterTime = setInterval(() => {
						that.tryLogin();
					}, 500);
				}
			},
			// 停止定时器（如果需要的话）  
			stopInterval() {
				if (this.InterTime !== null) {
					clearInterval(this.InterTime);
					this.InterTime = null;
				}
			},



			DownloadTbs() { // 安装内核tbs
				try {
					let HasTbs = open.isLoadTbs();
					// console.log(JSON.stringify(HasTbs))
					if (!HasTbs) {
						// 判断本地是否存在该路径文件
						if (uni.getStorageSync('tbsFile')) {
							uni.getFileInfo({
								filePath: uni.getStorageSync('tbsFile'),
								success: (res) => {
									console.log(res)
								},
								fail: (err) => {
									console.log(err)

									uni.downloadFile({
										url: this.Request.IPAgreement() + this.Request.serverIP() +
											'/download/arm64-v8a.tbs', //仅为示例，并非真实的资源
										success: (row) => {
											if (row.statusCode === 200) {
												let filepath = plus.io.convertLocalFileSystemURL(
													row
													.tempFilePath);
												uni.setStorageSync('tbsFile', filepath);

												// 安装文件浏览内核文件,安卓端需要
												open.installLocalTbs({
													tbsFilePath: filepath,
													isdelete: false //安装好是否要删除该文件
												}, function(e) {
													console.log(JSON.stringify(e))
												});
											}
										}
									});
								},
							})
						} else {

							uni.downloadFile({
								url: this.Request.IPAgreement() + this.Request.serverIP() +
									'/download/arm64-v8a.tbs', //仅为示例，并非真实的资源
								success: (res) => {
									if (res.statusCode === 200) {
										let filepath = plus.io.convertLocalFileSystemURL(res.tempFilePath);
										uni.setStorageSync('tbsFile', filepath);

										// 安装文件浏览内核文件,安卓端需要
										open.installLocalTbs({
											tbsFilePath: filepath,
											isdelete: false //安装好是否要删除该文件
										}, function(e) {
											console.log(JSON.stringify(e))
										});
									}
								}
							});

						}
					}

				} catch (e) {
					//TODO handle the exception
				}
			},
			GetOnlyIdentity() { // 获取本机唯一标识
				var that = this
				uni.setStorageSync('Only_Identity', uni.getSystemInfoSync()['deviceId']);
				that.Only_Identity = uni.getSystemInfoSync()['deviceId'];
			},
			isAllZero(str) { // 判断字符串是否都是 0，或者 ''
				// return /^0*$/.test(str.trim());
				return /^(0*|null)?$/.test((str || '').trim());
			},
			GetBusiness(data) { // 企业代号内容变化时,(加了个防抖)
				var that = this;

				// 如果 字符串全是 0 ，或者为空，把内容置空
				if (that.isAllZero(data)) {
					that.FormData.Business = '';
					return;
				}

				clearTimeout(that.Timer);

				that.Timer = setTimeout(() => {

					that.Request.request('AP_GetAccountByEnterNo', {
						EnterNo: data
					}, function(res) {
						if (res.status == 200) {


							if (res.data.ds.length) {
								res.data.ds.forEach(item => {
									item.text = item.AccountName;
									item.value = item.AccountID;
								});

								that.BusinessList = res.data.ds;
								let serviceIP = '';

								if (that.FormData.Business) {
									let index = res.data.ds.map((item) => item.value).indexOf(that.FormData
										.Business);

									if (index > 0) {
										that.FormData.Business = res.data.ds[index]['value'];
										serviceIP = res.data.ds[index].ServiceIP;
										that.Request.serverIP(res.data.ds[index].ServiceIP);
									} else {
										that.FormData.Business = res.data.ds[0]['value'];
										serviceIP = res.data.ds[0].ServiceIP;
										that.Request.serverIP(res.data.ds[0].ServiceIP);
									}
								} else {
									that.FormData.Business = res.data.ds[0]['value'];
									serviceIP = res.data.ds[0].ServiceIP;
									that.Request.serverIP(res.data.ds[0].ServiceIP);
								}

								that.GetHttp(serviceIP);

							} else {
								that.FormData.Business = '';
							}
						}
						// console.log(JSON.stringify(res))
					}, function(err) {
						console.log(JSON.stringify(err))
					}, 'http://' + that.Request.LoginIP() + '/Frame/SqlData', 1)

				}, 1000)

			},
			GetHttp(IP) { // 判断传入的IP地址，知道协议类型 :443 - 标准的 https 协议
				var that = this;
				let TheIP = 'http://'
				let TheIndex = IP.indexOf(':443');
				if (TheIndex != -1) {
					TheIP = 'https://'
				};
				that.Request.IPAgreement(TheIP)

			},
			SelectBusiness(data) { // 账套内容改变时 
				var that = this
				let FilterData = that.BusinessList.filter(item => {
					return item.AccountID == data
				})
				that.Request.serverIP(FilterData[0].ServiceIP);

				that.GetHttp(FilterData[0].ServiceIP)
			},
			checkboxChange(data) {
				var that = this;
				if (data.target.value.length) {
					that.Remember = true;
				} else {
					that.Remember = false;
				};

			},
			GetSelectFCJType() { // 查询公司报工类型
				let that = this;
				try {
					that.Request.request('SelectFCJType', {}, function(ret) {
						// console.log(ret.data.ds[0]['FCJType'])
						that.FCJType = ret.data.ds[0]['FCJType'];
						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'FCJType',
							data: ret.data.ds[0]['FCJType'],
							StorageName: 'FCJType',
							StorageData: ret.data.ds[0]['FCJType'],
						})
					})

				} catch (e) {
					//TODO handle the exception
				}
			},
			LoginApp() { // 登录
				var that = this;

				// 通过ref拿到校验结果
				this.$refs['baseForm'].validate().then(res => {
					// console.log('success', res);
					that.IsLoading = true
					let obj = {
						P_Name: that.FormData.UserAccount,
						P_Password: that.FormData.UserPwd,
						// cmd: 'applogin'
					}

					that.Request.request('applogin', obj, function(res) {

							that.DownloadTbs();

							if (res.data.ds[0].status == 200) {

								let UserInfo = res.data.ds[0];
								UserInfo.Business_Code = that.FormData.Business_Code;
								UserInfo.Business = that.FormData.Business;
								UserInfo.UserAccount = that.FormData.UserAccount;
								UserInfo.UserPwd = that.FormData.UserPwd;
								console.log(UserInfo);

								that.GetSelectFCJType(); // 查询公司报工类型

								if (that.Remember) {
									UserInfo.Remember = that.Remember;
								}

								// if (that.$store.state.UserInfo && that.$store.state.UserInfo.HeadshotImg) {
								// 	UserInfo.HeadshotImg = that.$store.state.UserInfo.HeadshotImg;
								// } else {
								// 	// 没有做头像上传，先默认是空的
								// 	UserInfo.HeadshotImg = '';
								// }

								that.$store.commit('ChangeAndSetStateData', {
									Name1: 'UserInfo',
									data: UserInfo,
									StorageName: 'UserInfo',
									StorageData: JSON.stringify(UserInfo),
								})

								setTimeout(() => {

									uni.showToast({
										title: res.data.ds[0].msg,
										icon: "none",
									})

									that.IsLoading = false

									// 自动登录
									uni.setStorageSync('Automatic_Login', true)

									// 查看授权
									that.searchApply()

									// 没授权接口的时候，用这个卡BUG，可以登，需要先登授权过的账套
									// uni.switchTab({
									// 	url: "/pages/index/index"
									// })
								}, 500)
							} else {
								console.log(res)
								uni.showToast({
									title: res.data.ds[0].msg,
									icon: "none",
									duration: 2000
								})
								that.IsLoading = false


								setTimeout(() => {
									uni.hideToast()
								}, 500)
							}

							setTimeout(() => {
								uni.hideToast()
							}, 2000)
						},
						function(err) {
							console.log(JSON.stringify(err))
							setTimeout(() => {

								uni.showToast({
									title: '请求失败 请检查后重试',
									icon: "none",
									duration: 2000
								})
								that.IsLoading = false
							}, 1000)
						}, that.Request.IPAgreement() + that.Request.serverIP() + '/Frame/ST1_SY/Handler.aspx',
						2)


				}).catch(err => {
					console.log('err', err);
					uni.showToast({
						title: "请完善信息",
						icon: "none",
						duration: 2000
					})


				})
			},
			searchApply() { // 产看本机是否授权
				var that = this
				let obj = {
					machineId: that.Only_Identity,
				}
				that.Request.request('searchapply', obj, function(res) {
					// console.log(JSON.stringify(res))
					if (res.status == 200) {
						if (res.data.ds.length) {
							// 已授权
							// that.$store.commit('ChangeAndSetStateData', {
							// 	Name1: 'Authorization',
							// 	data: true,
							// })

							let Authorization_Info = res.data.ds[0];
							Authorization_Info['Authorization'] = true;
							uni.setStorageSync('Authorization_Info', JSON.stringify(Authorization_Info));
							// console.log(Authorization_Info);
							// that.$store.commit('ChangeAndSetStateData', {
							// 	Name1: 'CreateTime',
							// 	data: res.data.ds[0].CreateTime.split('T')[0],
							// });
							// that.$store.commit('ChangeAndSetStateData', {
							// 	Name1: 'CreateTime',
							// 	data: res.data.ds[0].EffectiveDate.split('T')[0],
							// });

							if (process.env.NODE_ENV === 'development') {
								// console.log('开发环境'); // 发布到生产环境时，此处代码会被摇树移除掉。
							} else {
								// console.log('生产环境');

								// #ifdef APP-PLUS
								MAPPUpdate();
								// #endif
							}


							uni.redirectTo({
								url: "/pages/index/index" + '?index=' + 0
							});

						} else {
							uni.removeStorageSync('Authorization_Info')

							uni.redirectTo({
								url: "/pages/mine/OnlyIdentity?backBtn=" + 1
							});
						}

					}

				}, function(err) {
					console.log(JSON.stringify(err))
				}, that.Request.IPAgreement() + that.Request.serverIP() + '/Frame/SqlData', 1)
			},
		}
	}
</script>

<style lang="scss">
	.content {
		height: 100vh;
		display: flex;
		flex-direction: column;
		align-items: center;
		// justify-content: center;


		.LogoBox {
			height: 26vh;
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: flex-end;

			.Logo {
				display: flex;
				// justify-content: center;
				align-items: center;

				.img {
					// width: 100%;
					border-radius: 12rpx;
					overflow: hidden;
					// filter: drop-shadow(4px 8px 2px rgba(112, 112, 112, .2));
					filter: drop-shadow(4px 5px 2px rgba(112, 112, 112, .2));
				}

				.text {
					margin-left: 20rpx;
					font-size: 64rpx;
					color: #333;
					font-weight: 600;
					text-shadow: 2px 2px 3px #fff, 4px 4px 5px #999;
					letter-spacing: 2px;
				}
			}
		}

		.FormBox {
			min-height: 200px;
			width: 100%;
			// padding: 20px;

			// 表单内容
			.FormDataBox {
				width: 88%;
				margin: 0 auto;

				// 输入框上层类名
				.uni-easyinput__content {
					background-color: transparent !important;
					border: none !important;
					// border-bottom: 1px solid #c6c6c6 !important;
				}

				// 下拉框
				.uni-select {
					background-color: transparent !important;
					border: none !important;
					padding: 0 28rpx !important;

					.uni-select__selector {
						padding: 8px !important;

						.uni-select__selector-item {
							height: 50px !important;
							line-height: 50px !important;
						}
					}

					.uni-select__input-placeholder {
						color: #999;
					}
				}

				// 给底部增加一条线
				.uni-easyinput__content::after,
				.uni-select::after {
					position: absolute;
					box-sizing: border-box;
					content: ' ';
					pointer-events: none;
					right: 16px;
					bottom: 0;
					left: 16px;
					border-bottom: 1px solid #d8d8d8;
					-webkit-transform: scaleY(0.5);
					transform: scaleY(0.5);
				}

				.uni-easyinput__content-input {
					padding-left: 30rpx !important;
				}

				// 
				.u-checkbox__icon-wrap {
					background-color: transparent !important;
				}
			}
		}

		.BtnBox {
			width: 100%;

			.LoginBtn {
				background-color: #51d0d0;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 90%;
				margin: 0 auto;
				// color: #fff;

				.Text {
					margin-left: 10px;
				}
			}

			// 按钮的边框线在这里去除
			uni-button:after {
				border: none !important;
			}
		}

		// 复选框样式 start
		.uni-checkbox-input {
			border: 2px solid #d1d1d1 !important;
		}

		.uni-checkbox-input-checked {
			background: #51d0d0;
			color: #fff !important;
			border-color: #51d0d0 !important;
		}

		// 复选框样式 End

		// 底部文字
		.BottomText {
			position: absolute;
			bottom: 20px;
			left: 0;
			width: 100%;
			text-align: center;
			color: #a6a6a6;
			font-size: 12px;
		}
	}
</style>